<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Validator;


class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $data = array();      //向模板传递数据的公共变量
    protected $errors = array();    //数据验证错误信息

    protected function makeJsCode($code, $msg)
    {
        $data = array();
        $data['code'] = $code;
        $data['msg'] = $msg;
        return $data;
    }

    /**
     * 验证请求数据的合法性
     * return 成功返回true，失败返回false
     */
    protected function validateReq(Request $request, $rules, $msg = array())
    {
        $validator = Validator::make($request->all(), $rules, $msg);
        if ($validator->fails()) {
            $this->errors = $validator->errors();
            return false;
        } else {
            return true;
        }
    }

    /**
     * API接口数据返回
     * @param null $arr 约定好的数组格式
     * @return \Illuminate\Http\JsonResponse
     */
    protected function apiJson($arr = null)
    {
        if ($arr == null) {
            return response()->json($this->data);
        } else {
            return response()->json($arr);
        }
    }

}
